package net.wanho.shop.service.impl;

import cn.hutool.core.lang.UUID;
import com.aliyun.oss.OSSClient;
import lombok.SneakyThrows;
import net.wanho.shop.service.FileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class FileServiceImpl implements FileService {

    @Resource
    private OSSClient ossClient;

    @Value("${spring.cloud.alicloud.oss.bucket}")
    private String bucket;

    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endpoint;

    @SneakyThrows
    @Override
    public String upload(MultipartFile file) {
        String dir = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        String filename = file.getOriginalFilename();
        assert filename != null;
        String objectName = dir + "/" + UUID.randomUUID() + filename.substring(filename.lastIndexOf("."));

        ossClient.putObject(bucket, objectName, file.getInputStream());

        // https://fullstack126.oss-cn-nanjing.aliyuncs.com/fan2.png
//        String url = "https://" + bucket + "." + endpoint + "/" + objectName;
        return "https://" + bucket + "." + endpoint + "/" + objectName;
    }
}